package com.taobaostore.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.UUID;

import javax.tools.Tool;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
@SuppressWarnings("all")
public class FTPUtil {
	
	private static FTPClient client;
	private static String ip;
	private static int port;
	private static String username;
	private static String password;
	private static Properties properties;
	
	static {
		client = new FTPClient();
		ip = PropertiesUtil.getValue("FTP_IP");
		System.out.println("Ip上传地址是:"+ip);
		port = Integer.valueOf(PropertiesUtil.getValue("FTP_PORT"));
		username = PropertiesUtil.getValue("FTP_USERNAME");
		password = PropertiesUtil.getValue("FTP_PASSWORD");
	}
	
	public static void main(String[] args) {
		try {
			fileUpload("c532233e4234s2344345ggg345345.jpg", new FileInputStream(new File("C://Users/xzp/Desktop/课堂/涛宝商城成员信息/微信图片_20191009235418.jpg")));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally {
		}
		System.out.println("上传完毕");
	}
	
	
	/**
	 * 上传文件到ftp服务器
	 * @param file
	 * @return
	 */
	public static boolean fileUpload(String fileName,InputStream fileIn) {
		boolean flag = false;
        if (ServerConncetion(ip, port, username, password)) {
        	//设置为被动模式
			client.setBufferSize(1024);
			client.setControlEncoding("UTF-8");
			try {
				client.setFileType(FTPClient.BINARY_FILE_TYPE);
				client.enterLocalPassiveMode();
				client.changeWorkingDirectory("/img");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
        	System.out.println("连接成功!");
		    try {
				Boolean flag1 = client.storeFile(fileName,fileIn);
				System.out.println("上传结果:"+flag1);
				System.out.println(flag1);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				try {
					fileIn.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}

	/**
	 * FTP连接方法
	 * @param ip
	 * @param port
	 * @param username
	 * @param password
	 * @return
	 */
	public static boolean ServerConncetion(String ip,int port,String username,String password) {
		boolean flag = false;
		try {
			client.connect(ip, port);
			//设置为被动模式
			client.enterLocalPassiveMode();
			//设置上传文件的类型为二进制类型
			try {
				client.setFileType(FTP.BINARY_FILE_TYPE);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (client.login(username, password)) {
				flag = true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;   
	}
}
